﻿using UnityEngine;
using System.Collections;

public class Camera_FollowCharacter : MonoBehaviour {

	public Transform target;
	
	public float playerFollowSpeed;
	
	public Vector3 offsetDefault;
	public Vector3 rotDefault;

	Vector3 pos;
	public float[] posTarget=new float[3];
	
	
	Quaternion[] rot=new Quaternion[2];
	
	float[] fov=new float[2]{45f,45f};
	
	float[] moveSpeed=new float[2]{0f,3f};
	
	public void SetUp() {
		pos=(target.transform.position+(Vector3.up*0.6f)+(Vector3.forward*-1f));
		
		UpdateFollow();
		
		rot[0]=Quaternion.identity;
		rot[1]=Quaternion.Euler(rotDefault.x,rotDefault.y,rotDefault.z);
		
		DisplayCamera();
	}
		
	void Update () {
		
		moveSpeed[0]=Mathf.MoveTowards(moveSpeed[0],moveSpeed[1],(Time.deltaTime*moveSpeed[1]*0.5f));
		
		if(target){
			UpdateFollow();	
		}
	}
	
	void FixedUpdate(){
		UpdateMovement();
		DisplayCamera();
	}
	
	void UpdateFollow(){
		posTarget[0]=(target.transform.position.x+offsetDefault.x);
		posTarget[1]=(target.transform.position.y+offsetDefault.y);
		posTarget[2]=(target.transform.position.z+offsetDefault.z);
	}
	

	void UpdateMovement(){
		Vector3 posTargetV3=new Vector3(posTarget[0],posTarget[1],posTarget[2]);
		
		pos=Vector3.Lerp (pos,posTargetV3,(Time.deltaTime*moveSpeed[0]));
		
		rot[0]=Quaternion.Slerp (rot[0],rot[1],(Time.deltaTime*moveSpeed[0]));
		fov[0]=Mathf.Lerp (fov[0],fov[1],(Time.deltaTime*moveSpeed[0]));
	}
	
	void DisplayCamera(){
		transform.position=pos;
		transform.rotation=rot[0];
		camera.fieldOfView=fov[0];
	}
	
	public void SetTarget (Transform _target) {
		target=_target;
	}
}
